//
//  BLAnimation.swift
//  BLLiveTelecast
//
//  Created by BigL055 on 16/6/21.
//  Copyright © 2016年 bigL.liveTelecast.com. All rights reserved.
//

import UIKit

class BLAnimationView: UIView {
    
    var timer : NSTimer?
    var ImageView : UIImageView? = UIImageView()
    
    var flag : Bool = true
    
    var times : NSTimeInterval = 0.0
    
    
    
    
    /// 移除动画
    func removeAnimation() {
        self.userInteractionEnabled = false
        timer?.invalidate()
        ImageView?.removeFromSuperview()
//        self.removeFromSuperview()
    }

}

/// 房间开始加载动画
extension BLAnimationView{
    /// 开始加载动画
    func beginLoadingAnimation(duration : NSTimeInterval,speed : NSTimeInterval) {
        self.backgroundColor = UIColor.whiteColor()
        ImageView?.bl_setSize(CGSize(width: 151, height: 232))
        ImageView?.center = center
        self.addSubview(ImageView!)
        
        times = duration / speed
        self.userInteractionEnabled = true

        timer = NSTimer.scheduledTimerWithTimeInterval(speed, target: self, selector: #selector(waitForNetWorkData), userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)

    }
    
    
    func waitForNetWorkData() {
        
        times = times - 1
        flag = !flag
        if times < 0 {
            UIView.animateWithDuration(0.2, animations: {
                self.backgroundColor = UIColor.clearColor()
            })
            removeAnimation()
        }
        
        if flag {
            ImageView?.image = UIImage(named: "dyla_img_loading_1_151x232_")
        }else{
            ImageView?.image = UIImage(named: "dyla_img_loading_2_151x232_")
        }
    }
    
    func errorForNetWorkData() {
        
        ImageView?.image = UIImage(named: "dyla_img_loading_fail_189x205_")
        
    }

}
